using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;

namespace PackTracker.Business
{ 
	[Serializable()] 
	public class ItemPedido : Csla.BusinessBase<ItemPedido>
	{
		#region Business Properties and Methods

		//declare members
		private int _id = 0;
		private int _quantidade = 0;
		private string _rfid = string.Empty;
		private int _idProduto = 0;
		private int _idPedido = 0;

		//declare borrowed child member(s)
		private string _idProdutoDescricao;
		private SmartDate _idPedidoData;

		[System.ComponentModel.DataObjectField(true, true)]
		public int Id
		{
			get
			{
				CanReadProperty("Id", true);
				return _id;
			}
		}

		public int Quantidade
		{
			get
			{
				CanReadProperty("Quantidade", true);
				return _quantidade;
			}
			set
			{
				CanWriteProperty("Quantidade", true);
				if (!_quantidade.Equals(value))
				{
					_quantidade = value;
					PropertyHasChanged("Quantidade");
				}
			}
		}

		public string Rfid
		{
			get
			{
				CanReadProperty("Rfid", true);
				return _rfid;
			}
			set
			{
				CanWriteProperty("Rfid", true);
				if (value == null) value = string.Empty;
				if (!_rfid.Equals(value))
				{
					_rfid = value;
					PropertyHasChanged("Rfid");
				}
			}
		}

		public int IdProduto
		{
			get
			{
				CanReadProperty("IdProduto", true);
				return _idProduto;
			}
			set
			{
				CanWriteProperty("IdProduto", true);
				if (!_idProduto.Equals(value))
				{
					_idProduto = value;
					PropertyHasChanged("IdProduto");
				}
			}
		}

		public int IdPedido
		{
			get
			{
				CanReadProperty("IdPedido", true);
				return _idPedido;
			}
			set
			{
				CanWriteProperty("IdPedido", true);
				if (!_idPedido.Equals(value))
				{
					_idPedido = value;
					PropertyHasChanged("IdPedido");
				}
			}
		}

		public string idProdutoDescricao
		{
			get
			{
				CanReadProperty("idProdutoDescricao", true);
				return _idProdutoDescricao;
			}
		}

		public DateTime idPedidoData
		{
			get
			{
				CanReadProperty("idPedidoData", true);
				return _idPedidoData.Date;
			}
		}

		public string idPedidoDataString
		{
			get
			{
				CanReadProperty("idPedidoDataString", true);
				return _idPedidoData.Text;
			}
		}
 
		protected override object GetIdValue()
		{
			return _id;
		}

		#endregion //Business Properties and Methods

		#region Validation Rules
		private void AddCustomRules()
		{
			//add custom/non-generated rules here...
		}

		private void AddCommonRules()
		{
			//
			// Rfid
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Rfid");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Rfid", 50));
			//
			// IdProduto
			//
			ValidationRules.AddRule(CommonRules.IntegerMinValue, new CommonRules.IntegerMinValueRuleArgs("IdProduto", 1));
			//
			// IdPedido
			//
			ValidationRules.AddRule(CommonRules.IntegerMinValue, new CommonRules.IntegerMinValueRuleArgs("IdPedido", 1));
		}

		protected override void AddBusinessRules()
		{
			AddCommonRules();
			AddCustomRules();
		}
		#endregion //Validation Rules

		#region Authorization Rules
		protected override void AddAuthorizationRules()
		{
			//TODO: Define authorization rules in ItemPedido
			//AuthorizationRules.AllowRead("Id", "ItemPedidoReadGroup");
			//AuthorizationRules.AllowRead("Quantidade", "ItemPedidoReadGroup");
			//AuthorizationRules.AllowRead("Rfid", "ItemPedidoReadGroup");
			//AuthorizationRules.AllowRead("IdProduto", "ItemPedidoReadGroup");
			//AuthorizationRules.AllowRead("IdPedido", "ItemPedidoReadGroup");

			//AuthorizationRules.AllowWrite("Quantidade", "ItemPedidoWriteGroup");
			//AuthorizationRules.AllowWrite("Rfid", "ItemPedidoWriteGroup");
			//AuthorizationRules.AllowWrite("IdProduto", "ItemPedidoWriteGroup");
			//AuthorizationRules.AllowWrite("IdPedido", "ItemPedidoWriteGroup");
		}


		public static bool CanGetObject()
		{
			//TODO: Define CanGetObject permission in ItemPedido
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("ItemPedidoViewGroup"))
			//	return true;
			//return false;
		}

		public static bool CanAddObject()
		{
			//TODO: Define CanAddObject permission in ItemPedido
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("ItemPedidoAddGroup"))
			//	return true;
			//return false;
		}

		public static bool CanEditObject()
		{
			//TODO: Define CanEditObject permission in ItemPedido
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("ItemPedidoEditGroup"))
			//	return true;
			//return false;
		}

		public static bool CanDeleteObject()
		{
			//TODO: Define CanDeleteObject permission in ItemPedido
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("ItemPedidoDeleteGroup"))
			//	return true;
			//return false;
		}
		#endregion //Authorization Rules

		#region Factory Methods
		private ItemPedido()
		{ /* require use of factory method */ }

		public static ItemPedido NewItemPedido()
		{
			if (!CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a ItemPedido");
			return DataPortal.Create<ItemPedido>();
		}

		public static ItemPedido GetItemPedido(int id)
		{
			if (!CanGetObject())
				throw new System.Security.SecurityException("User not authorized to view a ItemPedido");
			return DataPortal.Fetch<ItemPedido>(new Criteria(id));
		}

		public static void DeleteItemPedido(int id)
		{
			if (!CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a ItemPedido");
			DataPortal.Delete(new Criteria(id));
		}

		public override ItemPedido Save()
		{
			if (IsDeleted && !CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a ItemPedido");
			else if (IsNew && !CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a ItemPedido");
			else if (!CanEditObject())
				throw new System.Security.SecurityException("User not authorized to update a ItemPedido");

			return base.Save();
		}

		#endregion //Factory Methods

		#region Child Factory Methods
		internal static ItemPedido NewItemPedidoChild()
		{
			ItemPedido child = new ItemPedido();
			child.ValidationRules.CheckRules();
			child.MarkAsChild();
			return child;
		}

		internal static ItemPedido GetItemPedido(SafeDataReader dr)
		{
			ItemPedido child =  new ItemPedido();
			child.MarkAsChild();
			child.Fetch(dr);
			return child;
		}
		#endregion //Child Factory Methods

		#region Data Access

		#region Criteria

		[Serializable()]
		private class Criteria
		{
			public int Id;

			public Criteria(int id)
			{
				this.Id = id;
			}
		}

		#endregion //Criteria

		#region Data Access - Create
		[RunLocal]
		protected override void DataPortal_Create()
		{
			ValidationRules.CheckRules();
		}

		#endregion //Data Access - Create

		#region Data Access - Fetch
		private void DataPortal_Fetch(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteFetch(cn, criteria);
			}//using
		}

		private void ExecuteFetch(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_GetItemPedido";
				cm.Parameters.AddWithValue("@id", criteria.Id);

				using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
				{
					dr.Read();
					FetchObject(dr);
					ValidationRules.CheckRules();

					//load child object(s)
					FetchChildren(dr);
				}
			}//using
		}

		#endregion //Data Access - Fetch

		#region Data Access - Insert
		protected override void DataPortal_Insert()
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteInsert(cn);

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		#endregion //Data Access - Insert

		#region Data Access - Update
		protected override void DataPortal_Update()
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				if (base.IsDirty)
				{
					ExecuteUpdate(cn);
				}

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		#endregion //Data Access - Update

		#region Data Access - Delete
		protected override void DataPortal_DeleteSelf()
		{
			DataPortal_Delete(new Criteria(_id));
		}

		private void DataPortal_Delete(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteDelete(cn, criteria);

			}//using

		}

		private void ExecuteDelete(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_DeleteItemPedido";

				cm.Parameters.AddWithValue("@id", criteria.Id);

				cm.ExecuteNonQuery();
			}//using
		}
		#endregion //Data Access - Delete

		#region Data Access - Fetch
		private void Fetch(SafeDataReader dr)
		{
			FetchObject(dr);
			MarkOld();
			ValidationRules.CheckRules();

			//load child object(s)
			if(!this.IsChild)
				FetchChildren(dr);
		}

		private void FetchObject(SafeDataReader dr)
		{
			_id = dr.GetInt32("id");
			_quantidade = dr.GetInt32("Quantidade");
			_rfid = dr.GetString("RFID");
			_idProduto = dr.GetInt32("idProduto");
			_idPedido = dr.GetInt32("idPedido");
			_idProdutoDescricao = dr.GetString("idProdutoDescricao");
			_idPedidoData = dr.GetSmartDate("idPedidoData", _idPedidoData.EmptyIsMin);
		}

		private void FetchChildren(SafeDataReader dr)
		{
		}
		#endregion //Data Access - Fetch

		#region Data Access - Insert
		internal void Insert(SqlConnection cn)
		{
			if (!IsDirty) return;

			ExecuteInsert(cn);
			MarkOld();

			//update child object(s)
			UpdateChildren(cn);
		}

		private void ExecuteInsert(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_AddItemPedido";

				AddInsertParameters(cm);

				cm.ExecuteNonQuery();

				_id = (int)cm.Parameters["@id"].Value;
			}//using
		}

		private void AddInsertParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@Quantidade", _quantidade);
			cm.Parameters.AddWithValue("@RFID", _rfid);
			cm.Parameters.AddWithValue("@idProduto", _idProduto);
			cm.Parameters.AddWithValue("@idPedido", _idPedido);
			cm.Parameters.AddWithValue("@id", _id);
			cm.Parameters["@id"].Direction = ParameterDirection.Output;
		}
		#endregion //Data Access - Insert

		#region Data Access - Update
		internal void Update(SqlConnection cn)
		{
			if (!IsDirty) return;

			if (base.IsDirty)
			{
				ExecuteUpdate(cn);
				MarkOld();
			}

			//update child object(s)
			UpdateChildren(cn);
		}

		private void ExecuteUpdate(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_UpdateItemPedido";

				AddUpdateParameters(cm);

				cm.ExecuteNonQuery();

			}//using
		}

		private void AddUpdateParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@id", _id);
			cm.Parameters.AddWithValue("@Quantidade", _quantidade);
			cm.Parameters.AddWithValue("@RFID", _rfid);
			cm.Parameters.AddWithValue("@idProduto", _idProduto);
			cm.Parameters.AddWithValue("@idPedido", _idPedido);
		}

		private void UpdateChildren(SqlConnection cn)
		{
		}
		#endregion //Data Access - Update

		#region Data Access - Delete
		internal void DeleteSelf(SqlConnection cn)
		{
			if (!IsDirty) return;
			if (IsNew) return;

			ExecuteDelete(cn, new Criteria(_id));
			MarkNew();
		}
		#endregion //Data Access - Delete
		#endregion //Data Access
	}
}
